<?php
namespace Home\Controller;
use Think\Controller;
use Home\Controller\BaseController;
class IndexController extends BaseController {

	//首页
    public function index(){
        //迷笛先生
    	$data['mrmidi_user_id'] = array('IN','40,75,76,96,140,532');
    	$mrmidi_arr = M('mrmidi')->alias('m')->field('mrmidi_major_id,mrmidi_level,user_name,user_avatar,user_introduction')->join('midi_user as u on u.user_id = m.mrmidi_user_id')->where($data)->select();
    	$this->assign('mrmidi_arr',$mrmidi_arr);
        //新闻3条
        $news_arr = M('news')->limit(3)->order('news_id desc')->select();
        $this->assign('news_arr',$news_arr);
        //考级详情
        $article_arr = M('article')->where(['article_id'=>52])->find();
        $this->assign('article_arr',$article_arr);
        $this->display();
    }

	//用户信息
    public function userinfo(){
    	//如果session存在，传递用户信息
    	$midiuser = session('midiuser');
    	if (!empty($midiuser)) {
    		$this->assign('midiuser',$midiuser);
    	}else{
    		$this->error('您尚未登录，请去登录','login');
    	}
    	if(IS_POST){
            $data = I('post.');
            if($data != array_filter($data)){
                $this->error('信息必须填写完整！','userinfo');
            }
            //判断是否有图片上传
            if($_FILES['file']['size'] > 0){
                $finfo = upload($_FILES['file']);
                if ($finfo['status'] == 0) {
                    $this->error($finfo['msg'],'userinfo'); //上传失败
                }else{
                    $data['user_avatar'] = $finfo['filepath'];
                }
            }
            if(!check_email($data['user_email'])){
                $this->error('邮箱格式不正确！','userinfo');
            }
            $user_model = M('user');
            $wh['user_email'] = array('eq',$data['user_email']);
            $wh['user_id'] = array('neq',$midiuser['user_id']);
            if($user_model->where($wh)->find()){
                $this->error('邮箱已被使用','userinfo');
            }
            $data['user_id'] = $midiuser['user_id'];
            $res = $user_model->save($data);
            if($res){
                $this->success('修改成功！','userinfo');
            }else{
                $this->error('没有修改内容或刷新重试！','userinfo');
            }
        }else{
    	    $info = M('user')
                ->field('user_id,user_nickname,user_avatar,user_email,user_sex,user_birthday,user_nation')
                ->find($midiuser['user_id']);
    	    $this->assign('info',$info);
            $this->display();
        }
    }

    //修改密码
    public function vip_pwd()
    {
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if (!empty($midiuser)) {
            $this->assign('midiuser',$midiuser);
        }else{
            $this->error('您尚未登录，请去登录','login');
        }
        if(IS_POST){
            $data = I('post.');
            if(!isMobile($data['user_phone'])){
                $this->error('手机号格式不正确！','vip_pwd');
            }
            $user_model = M('user');
            if($find = $user_model->where(['user_phone'=>$data['user_phone']])->find()){
                $pwd_preg = '/^\w{6,16}$/';
                if(!preg_match($pwd_preg,$data['user_password'])){
                    $this->error('密码格式不符！','vip_pwd');
                }
                if($data['user_password'] != $data['password']){
                    $this->error('两次密码不一致！','vip_pwd');
                }
                $data['user_password'] = md5($data['user_password']);
                if($data['user_password'] == $find['user_password']){
                    $this->error('与原密码一致！','vip_pwd');
                }
                $res = $user_model
                    ->where(['user_id'=>$midiuser['user_id'],'user_phone'=>$data['user_phone']])
                    ->save(['user_password'=>$data['user_password']]);
                if($res){
                    $this->success('操作成功！','vip_pwd');
                }else{
                    $this->error('操作失败,请刷新重试！','vip_pwd');
                }
            }else{
                $this->error('该手机号还未注册！','vip_pwd');
            }
        }else{
            $this->display();
        }
    }
    //修改密码时，发送手机验证码
    public function sendPhoneCodePwd()
    {
        $phone = I('post.user_phone');
        if(!isMobile($phone)){
            $this->ajaxReturn(['status'=>2,'msg'=>'手机号格式不正确']);
        }
        if($find = M('user')->where(['user_phone'=>$phone])->find()){
            $code = createRandomCode(4);
            alidayucode($code, $phone); //发送短信
            $this->ajaxReturn(['status'=>1,'msg'=>'获取短信验证码成功','data'=>$code]);
        }else{
            $this->ajaxReturn(['status'=>3,'msg'=>'该手机号未注册']);
        }
    }

    //添加收货地址
    public function vip_address()
    {
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if (!empty($midiuser)) {
            $this->assign('midiuser',$midiuser);
        }else{
            $this->error('您尚未登录，请去登录','login');
        }
        if(IS_POST){
            $data = I('post.');
            if(empty($data['address_username']) ||
            empty($data['address_zipcode']) ||
            empty($data['address_userphone'])){
                $this->error('信息不全！','vip_address');
            }
            if(!isMobile($data['address_userphone'])){
                $this->error('手机号格式不正确！','vip_address');
            }
            if(empty($data['address_detail'])){
                $this->error('地址信息填写不完整！','vip_address');
            }else{
                $data['address_address'] = $data['province3'].$data['city3'].$data['area3'].$data['address_detail'];
            }
            $address_model = M('address');
            if($data['address_default'] > 0){
                $def = $address_model
                    ->where(['address_user_id'=>$midiuser['user_id']])
                    ->save(['address_default'=>0]);
            }
            if($data['id'] > 0){
                $data['address_id'] = $data['id'];
                $data['address_user_id'] = $midiuser['user_id'];
                $res = $address_model
                    ->save($data);
            }else{
                $data['address_user_id'] = $midiuser['user_id'];
                $res = $address_model->add($data);
            }
            if($res){
                $this->success('操作成功！','vip_address');
            }else{
                $this->error('操作失败,或未作修改！','vip_address');
            }
        }else{
            $address_list = M('address')
                ->field('address_display',true)
                ->where(['address_user_id'=>$midiuser['user_id'],'address_display'=>1])
                ->select();
            $this->assign('address_list',$address_list);
            $this->display();
        }
    }
    //删除收货地址
    public function del_address()
    {
        //如果session存在，传递用户信息
        $midiuser = session('midiuser');
        if (!empty($midiuser)) {
            $this->assign('midiuser',$midiuser);
        }else{
            $this->error('您尚未登录，请去登录','login');
        }
        if(IS_AJAX){
            $id = I('id',0,'intval');
            if($id > 0){
                $res = M('address')->save([
                    'address_id'=>$id,
                    'address_user_id'=>$midiuser['user_id'],
                    'address_display'=>0,
                ]);
            }else{
                $this->error('操作失败，请刷新重试！','vip_address');
            }
        }
    }

    //登录
    public function login(){
        $url = $_SERVER['HTTP_REFERER'];
        $this->assign('url',$url);
    	$this->display();
    }

    //登录操作
    public function login_action(){
    	if (empty($_POST['user_id']) || empty($_POST['user_password'])) {
    		$this->error('账号或密码不能为空');
    	}
    	if($_POST['user_id'] > 10000000){
            $_POST['user_phone'] = $_POST['user_id'];
            unset($_POST['user_id']);
        }
        $_POST['user_password'] = md5($_POST['user_password']);
        if($user_arr = M('user')->where($_POST)->find()){
            $data['user_last_time'] = date('Y-m-d H:i:s',time());
            $data['user_id'] = $user_arr['user_id'];
            // $data['user_token'] = $this->createRandom();
            M('user')->save($data);
            $user_arr = M('user')->field('user_id,user_phone,user_nickname,user_avatar')->where('user_id = '.$data['user_id'])->find();
            //用户信息存入session
            session('midiuser',$user_arr);
            $this->success('登录成功',$_POST['url'] ? $_POST['url'] : U('Home/Index/index'));
        }else{
            $this->error('账号或密码错误');
        }
    }

    //退出登录
    public function logout(){
    	unset($_SESSION['midiuser']);
    	$this->success('退出成功','index');
    }

    //注册
    public function register(){

    	$this->display();
    }

    // 生成验证码
    public function showVerify(){
        show_verify();
    }



    /**
     * 注册操作
     * @author xuan
     * @param verify    	验证码（必填）
     * @param user_phone    手机号码（必填）
     * @param user_password 密码（必填）
     */
    public function register_action(){

        // if (!check_verify($_POST['verify'])) {
        //     $this->error('验证码输入错误！');
        // }

        $data['user_phone'] = $_POST['user_phone'];
        if(M('user')->where($data)->find()){
            $this->error('号码已被注册');
        }
        $_POST['user_nickname'] = phonenumHidden($_POST['user_phone']);
        $_POST['user_reg_time'] = date('Y-m-d H:i:s',time());
        $_POST['user_password'] = md5($_POST['user_password']);
        if($data['user_id'] = M('user')->data($_POST)->add()){
            $user_arr = M('user')->field('user_id,user_phone,user_nickname,user_avatar')->where('user_id = '.$data['user_id'])->find();
            //用户信息存入session
            session('midiuser',$user_arr);
            $this->success('注册成功','index');
        }else{
            $this->error('注册失败');
        }
    }

    /**
     * 重置密码
     * @author xuan
     * @param user_phone    手机号码（必填）
     * @param user_password 密码（必填）
     */
    public function resetPassword(){

        // if (!check_verify($_POST['verify'])) {
        //     $this->error('验证码输入错误！');
        // }

        $data['user_phone'] = $_POST['user_phone'];
        $user = M('user')->field('user_id')->where($data)->find();
        if (empty($user)) {
            $this->error('该手机号码未被注册');
        }
        $user['user_password'] = md5($_POST['user_password']);
        M('user')->save($user);
        $this->success('重置密码成功，请重新登录！','login');

    }
}